# coding=utf-8
import os

from django.http import HttpResponseRedirect
from django.db import transaction
from op_drf.filters import DataLevelPermissionsFilter
from .handler import *
from django.shortcuts import render
from loguru import logger
from rest_framework.request import Request
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, status

from datetime import datetime
import requests

from apps.prescription.filters import PrescriptionFilter, DrugFilter
from op_drf.pagination import Pagination
from op_drf.response import SuccessResponse, ErrorResponse

from op_drf.dj_utils import set_delete, create_by_serializer
from op_drf.viewsets import CustomModelViewSet
from apps.prescription.models import Prescription, Drug
from apps.prescription.serializers import WritePrescriptionSerializer, ReadPrescriptionSerializer, WriteDrugSerializer, \
    ReadDrugSerializer
from op_drf.viewsets import ModelViewSet
from ..TabletInfo.models import TabletInfo


# Create your views here.

class PrescriptionView(CustomModelViewSet):
    """
    处方信息的CRUD
    """
    queryset = Prescription.objects.filter(is_delete=False)
    serializer_class = ReadPrescriptionSerializer  # 序列化器
    create_serializer_class = WritePrescriptionSerializer
    update_serializer_class = WritePrescriptionSerializer
    # 分页
    pagination_class = Pagination
    # 筛选
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = PrescriptionFilter
    search_fields = ("id", )
    filter_fields = ("id", )
    ordering_fields = ("-id",)
    ordering = ["-create_datetime"]

    def create(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        # MedItem = request.data.pop("MedItem", None)
        MedItem = request.data.get("MedItem", None)
        assert MedItem,f"参数错误，未传入药品信息"
        logger.debug(1)

        serializer = self.get_serializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        id = serializer.data.get("id","0")

        # 批量添加药品及服药方式

        logger.debug(MedItem)
        if MedItem:
            drug_data = []
            logger.debug(MedItem)
            if MedItem:
                MedItem = MedItem[0]
                logger.debug(MedItem)
                mednm = MedItem.get("MedNm",None)
                logger.debug(mednm)
                meditemdose = MedItem.get("MedItemDose",None)
                assert meditemdose,f"{mednm}缺少服药方式"
                MedUnit = MedItem.get("MedUnit", None)
                MedNote = MedItem.get("MedNote", None)

                DoseList_time = meditemdose.get("doseList_time",None)
                DoseList_dose = meditemdose.get("doselist_dose",None)
                takedays = meditemdose.get("TakeDays",None)
                drtscd = meditemdose.get("drtscd",None)
                takedt = meditemdose.get("takedt",None)
                logger.debug(1)
                drug_data.append({"MedNm":mednm,
                                  "MedUnit":MedUnit,
                                    "MedNote":MedNote,
                                    "doselist_time":DoseList_time,
                                    "doselist_dose":DoseList_dose,
                                    "takedays":takedays,
                                    "drtscd":drtscd,
                                    "takedt":takedt,
                                    "prescrption":id})
                # 批量添加药品
                logger.debug(drug_data)
                drug_serializer = create_by_serializer(
                    WriteDrugSerializer, data=drug_data, context=self.get_serializer_context(),many=True
                )
                logger.debug(1)
            else:
                logger.debug(MedItem)
                logger.debug(type(MedItem))
                logger.debug("没药品")

            # 同时写入xml
            try:
                id = serializer.data.get("id",0)
                atmtorad(id)
                if AUTO_SERVE:
                    atmtorad()
            except Exception as e:
                # return ErrorResponse(msg="ftp配置错误请检查！")
                pass
        else:
            logger.debug("无药品")
        return SuccessResponse(serializer.data, headers=headers)

    def update(self, request: Request, *args, **kwargs):
        # logger.debug("前端传入的数据： %s" % request.data)
        # logger.debug("请求携带的数据： %s" % kwargs)
        instance = self.get_object()
        msg = ""
        if not instance:
            msg = "请确定要修改的药方"
            return ErrorResponse(msg=msg)
        is_active = request.data.get("is_active", None)
        if not is_active:
            return ErrorResponse(msg="未设置药单状态")
        if instance and is_active:
            if str(instance.is_active) == is_active:
                return ErrorResponse(msg="不允许重复修改药方状态")
            else:
                instance.is_active = True if is_active == "1" else False
                instance.save()
                logger.debug(type(is_active))
                if is_active=="1":
                    msg = f"已确定使用该药方"
                    logger.debug(msg)
                else:
                    msg = f"已取消使用该药方"
                    logger.debug(msg)

        return SuccessResponse(msg=msg)

    # 根据数据生成xml文件
    def Create_YF(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)

        atmtorad()


    def Create_drug(self, request: Request,drug_data, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        logger.debug("请求携带的药品数据： %s" % drug_data)



class DrugView(CustomModelViewSet):
    """
    处方信息的CRUD
    """
    queryset = Drug.objects.filter(is_delete=False)
    serializer_class = ReadDrugSerializer  # 序列化器
    create_serializer_class = WriteDrugSerializer
    update_serializer_class = WriteDrugSerializer
    # 分页
    pagination_class = Pagination
    # 筛选
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = DrugFilter
    search_fields = ("id", )
    filter_fields = ("id", )
    ordering_fields = ("-id",)
    ordering = ["-create_datetime"]

    def create(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)

        tabletinfo_id = request.data.get("tablet_info",0)
        if tabletinfo_id:
            tabletinfo = TabletInfo.objects.filter(pk=tabletinfo_id)
            if tabletinfo:
                tablet_obj = tabletinfo[0]
                logger.debug(tablet_obj.tblt_nm)
                request.data["MedNm"] = tablet_obj.tblt_nm
                tblt_cd = "cd"
                request.data["MedCd"] = tblt_cd
                request.data["MedUnit"] = "粒"
        prescrption_id = request.data.get("prescrption",0)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        logger.debug("序列化后的数据： %s" % serializer.data)
        return SuccessResponse(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def service_rad(request):
    atmtorad()
    return HttpResponseRedirect('/user/login')

def selfcreate(request):
    # 当前登录用户
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    # 新增自编方数据表
    prescription = Prescription.objects.filter(is_delete=False,is_active=True, OrderStatus="0", OrderType="0",user__id=user_id)
    logger.debug(1)
    if prescription:
        logger.debug(1)
        prescription_obj = prescription[0]
    else:
        logger.debug(1)
        staruser_obj = StarUser.objects.filter(pk=user_id)[0]
        prescription_obj = Prescription.objects.create(OrderDt=datetime.now(),
                                                       OrderNum=datetime.now().strftime("%Y%m%d%H%M%S"),
                                                       OrderDtm=datetime.now(),
                                                       OrderType="0",
                                                       user=staruser_obj)
    logger.debug(1)
    tablet_info = TabletInfo.objects.all()
    logger.debug(1)
    context = {"OrderDt":prescription_obj.OrderDt.strftime("%Y-%m-%d"),
               "OrderNum":prescription_obj.OrderNum,
               "prescription_id":prescription_obj.pk,
               "tablet_info_list":tablet_info}
    logger.debug(1)
    return render(request, os.path.join("prescription","self_prescrip.html"), context)


def buy_med(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    context = {'user_id':user_id}
    return render(request,os.path.join("prescription","buymed.html"),context)

def zhenliao(request):
    context = {}
    return render(request,'zhenliao.html',context)

def pengsong(request):
    context = {}
    return render(request,'peisong.html',context)